package cn.edu.nju.software;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;

public class GetMessage {
	private String filePath;
	private Socket socket;
	private int type;
	private String fromServer;
	
	public GetMessage(Socket socket, String filePath) {
		this.filePath= filePath;
		this.socket = socket;
		getMessage();
	}

	private void getMessage() {
		// TODO Auto-generated method stub
		int bufferSize = 8192;
		byte[] buf = new byte[bufferSize];
		
		try {
			DataInputStream inputStream  = new DataInputStream(
					new BufferedInputStream(socket.getInputStream()));
			
			type = inputStream.readInt();
			fromServer = inputStream.readUTF();
			
			DataOutputStream fileOut = new DataOutputStream(
					new BufferedOutputStream(new BufferedOutputStream(
							new FileOutputStream(filePath))));
			
			while(true) {
				int read = 0;
				if (inputStream != null) {
					read = inputStream.read(buf);
				}
				if (read == -1)
					break;
				
				fileOut.write(buf, 0, read);
			}
			System.out.println("The request has been recevied. Waiting for swaping......");
			
			fileOut.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int getType() {
		return type;
	}
	
	public String getFromServer() {
		return fromServer;
	}
}
